<?php
namespace app\admin\controller;

use think\Controller;


class Upload extends Controller
{
    /**
     * Author：Domino
     * Date: 2019/10/9
     * Time: 18:20
     * @todo 上传图片
     * @param file $image 图片信息
     * @param string $event 事件:avatar=头像(默认200*200裁剪)
     * @return \think\response\Json
     */
    public function image()
    {
        if ($this->request->isPost()) {
            $file = $this->request->file('file');
            if (is_null($file)) {
                putMsg(0, '文件信息获取失败');
            }
            $event = $this->request->param('event', 'image');
            $savePath = './uploads/'.$event.'/' . date("Ymd") . "/";
            if (!is_dir($savePath)) {
                mkdir($savePath, 0777, true);
            }
            $info = $file->rule('uniqid')->validate(['ext' => 'jpg,png,jpeg'])->move($savePath);
            if ($info) {
                $fileName = $info->getFilename();
                $filePath = str_replace("./", "/", $savePath . $fileName);
                // 图像缩略图
                $resize = [];
                switch ($event) {
                    case 'avatar':
                        $resize[] = [110, 110];
                        $thumb_width = 110;
                        $thumb_height = 110;
                        break;
                }
                if ($event != 'image') {
                    create_thumb($filePath, $resize);
                    return json(['code'=>1, 'msg'=>$file->getError(), 'data'=> ['image'=>$filePath, 'thumb_image'=>get_thumb_img($filePath, $thumb_width, $thumb_height)[0]]]);
                } else {
                    return json(['code'=>1, 'msg'=>$file->getError(), 'data'=> ['image'=>$filePath]]);
                }
            } else {
                return json(['code'=>0, 'msg'=>$file->getError()]);
            }
        }
        return json(['code'=>0, 'msg'=>'请求类型错误']);
    }

}